package edu.hcnu.common;

import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @ClassName IdGenerator
 * @Description TODO
 * @Author liang
 * @Date 2023/4/30 13:27
 * @Version 1.0
 **/
public class IdGenerator {
    private final static int RADIX = 36;
    private final static int LENGTH = 8;
    private static volatile IdGenerator instance;
    private static final Object LOCK = new Object();
    private int sequence = 0;

    private IdGenerator() {}

    public static IdGenerator getInstance() {
        // 双重检查锁定
        if (instance == null) {
            synchronized (LOCK) {
                if (instance == null) {
                    instance = new IdGenerator();
                }
            }
        }
        return instance;
    }

    public synchronized String generate() {
        long now = System.currentTimeMillis();
        StringBuilder idBuilder = new StringBuilder(Long.toString(now, RADIX));
        while (idBuilder.length() < LENGTH) {
            idBuilder.insert(0, '0');
        }
        if (sequence >= 10000) {
            sequence = 0;
        }
        idBuilder.append(sequence++);
        return idBuilder.toString().toUpperCase();
    }
}
